package com.example.bingobox.ui.todobox;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.bingobox.R;
import com.example.bingobox.model.Task;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class TodoListAdapter extends RecyclerView.Adapter<TodoListAdapter.ViewHolder> {
    private final List<Task> tasks;
    private final OnTaskStatusChangedListener listener;

    public interface OnTaskStatusChangedListener {
        void onStatusChanged(Task task);
    }

    public TodoListAdapter(List<Task> tasks, OnTaskStatusChangedListener listener) {
        this.tasks = tasks;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_todo, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Task task = tasks.get(position);
        
        holder.checkBox.setChecked(task.isCompleted());
        holder.nameText.setText(task.getName());
        holder.descriptionText.setText(task.getDescription());
        holder.deadlineText.setText(formatDate(task.getDeadline()));
        
        holder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            task.setCompleted(isChecked);
            if (listener != null) {
                listener.onStatusChanged(task);
            }
        });
    }

    @Override
    public int getItemCount() {
        return tasks.size();
    }

    private String formatDate(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        CheckBox checkBox;
        TextView nameText;
        TextView descriptionText;
        TextView deadlineText;

        ViewHolder(View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.checkbox_todo);
            nameText = itemView.findViewById(R.id.text_todo_name);
            descriptionText = itemView.findViewById(R.id.text_todo_description);
            deadlineText = itemView.findViewById(R.id.text_todo_deadline);
        }
    }
} 